<!--
* <p>Title:部门树状图</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2
* <p>Company: 深圳市智慧城市管家信息科技有限公司
* @author 蒋松 - Alter
* @version v1.0 2017年2月23日
*-->
<template>
    <div class="el-select">
        <el-tooltip class="item" effect="dark" :content="getResults" placement="bottom">
            <div class="el-input" :class="{'is-disabled': disabled}" @click="hanldeVisible">
                <i class="el-input__icon el-icon-caret-top" :class="{'is-reverse': isReverse}"></i>
                <input
                    ref="input"
                    v-model="getResults"
                    autocomplete="off"
                    placeholder="请选择"
                    readonly="readonly"
                    :disabled="disabled"
                    type="text"
                    class="el-input__inner">
            </div>
        </el-tooltip>
        <el-dialog v-model="visible" v-transfer-dom>
            <!-- 筛选 -->
            <div style="display:inline-block" slot="title">
                <el-form :inline="true" :model="filters">
                    <el-form-item>
                        <el-input v-model="filters.keyword" placeholder="姓名/角色/部门/手机号码" style="width:300px;"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="search" @click="handleSearch">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-row v-if="multiple">
                <!-- 选中集合 -->
                <el-col class="mtb15 departBox">
                    <div v-for="(item, index1) in results" :key="item.deptid">
                        <p class="deptName">{{ item.deptName + '：' }}</p>
                        <div class="el-select" style="width: 100%;">
                            <span>
                                <span v-for="(role, index2) in item.selecteUserList" :key="role.id" class="el-tag el-tag--primary">
                                    <span class="el-select__tags-text">{{ role.realname }}</span>
                                    <i class="el-tag__close el-icon-close" @click="handleRemove(index1, index2)"></i>
                                </span>
                            </span>
                        </div>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" :class="{mt15: !multiple}">
                <!-- 树 -->
                <el-col :span="8">
                    <el-tree
                        :data="regions"
                        :props="props"
                        node-key="id"
                        check-strictly
                        highlight-current
                        ref="tree"
                        @node-click="handleNodeClick"
                        :render-content="renderContent"
                        style="height:400px;overflow:auto;padding:10px;"
                        >
                    </el-tree>
                </el-col>
                <!-- 表 -->
                <el-col :span="16">
                    <el-table
                    :data="userList"
                    v-loading="listLoading"
                    @select="handleTableSelect"
                    @row-click="handleRowClick"
                    @select-all="handleSelectAll"
                    highlight-current-row border stripe class="w100" :max-height="400">
                        <el-table-column type="selection" width="40" v-if="multiple"></el-table-column>
                        <el-table-column prop="realname" label="姓名" width="120"></el-table-column>
                        <el-table-column prop="roleName" label="角色" width="150"></el-table-column>
                        <el-table-column prop="deptName" label="部门" width="150"></el-table-column>
                        <el-table-column prop="mobile" label="手机号码" width="140"></el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!-- 按钮 -->
            <el-col slot="footer" class="fr mb15" v-if="multiple">
                <el-button @click="hanldeCancle">取消</el-button>
                <el-button type="primary"@click="hanldeConfirm">确定</el-button>
            </el-col>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'scEmployeeTree',
    props: {
        value: {
            type: Array,
            default: function(){
                return []
            }
        },
        disabled: {
            type: Boolean,
            default: false
        },
        multiple: {
            type: Boolean,
            default: false
        }//多选
    },
    data() {
        return {
            isReverse: false,
            visible: false,
            listLoading: false,
            filters: {
                keyword: ''
            },//表单
            regions: [],//部门树
            userList: [],//员工表
            props: {
                label: 'name',
                children: 'childDepartment'
            },
            curDepartId: '',//当前选中的部门id
            curDepartName: '',//当前选中部门名字
            results: this.value,//结果集
            oldResults: []
        }
    },
    computed:{
        getResults: function(){
            let str = ''
            this.results.forEach((item) => {
                item.selecteUserList.forEach((role, index) => {
                    str += role.realname + '，'
                })
            })
            return str.substring(0, str.length -1)
        }
    },
    created(){
        let vm = this
        queryDepartTree({}).then((res) => {
            if (res.status === 10000) {
                let data = res.data
                vm.regions = data.datalist
            } else {
                vm.$message({
                    showClose: true,
                    message: res.info,
                    type: 'error'
                })
            }
        })
    },
    methods: {
        //设置编辑值

        setValue(value){
            this.results = value;
        },
        //显示影藏弹窗
        hanldeVisible(){
            if(this.disabled) return
            this.oldResults = JSON.parse(JSON.stringify(this.results))
            this.isReverse = !this.isReverse
            this.visible = !this.visible
        },
        //点击部门树子选项
        handleNodeClick(data) {
            let arr = []
            arr.push(data)
            this.resetChecked()
            this.setCheckedNodes(arr)
            this.queryListById(data)
        },
        //让树指定值勾选
        setCheckedNodes(node){
            this.$refs.tree.setCheckedNodes(node)
        },
        //清除树
        resetChecked() {
            this.$refs.tree.setCheckedNodes([]);
        },
        //重置
        reset(){
            this.visible = false
            this.results = []
        },
        //筛选
        handleSearch(){
            let vm = this,
                departInfo = {
                    id: vm.curDepartId, //当前员工列表的部门
                    name: vm.curDepartName
                }
            vm.queryListById(departInfo)
        },
        //重置
        handleReset(){
            let vm = this
            vm.resetChecked()
            vm.curDepartId = ""
            vm.curDepartName = ""
            vm.userList = []
            vm.filters.keyword = ""
        },
        //点击右上角小×删除选中的值
        handleRemove(index1, index2){
            let arr = this.results[index1].selecteUserList
            arr.splice(index2, 1)
            if(arr.length === 0){
                this.results.splice(index1, 1)
            }
        },
        //全选情况
        handleSelectAll(selection){
            this.handleTableSelect(selection)
        },
        //单选情况
        handleTableSelect(selection){
            let vm = this
            //如果当前部门下没人 移除这个部门
            if(selection.length === 0) {
                vm.results.forEach((item, index) => {
                    if(item.deptid === vm.curDepartId){
                        vm.results.splice(index, 1)
                    }
                })
                return
            }
            //否则 将这个部门下选中的放进结果
            vm.results.push({
                deptid: selection[0].deptid,
                deptName: selection[0].deptName,
                selecteUserList: selection
            })
            //结果去重
            vm.results = vm.unique(vm.results, 'deptid')
        },
        //点击表格
        handleRowClick(row, event, column){
            if(this.multiple) return
            this.results = [{
                deptid: this.curDepartId,
                deptName: this.curDepartName,
                selecteUserList: [row]
            }]
            this.visible = false
        },
        //取消
        hanldeCancle(){
            this.reset()
            this.results = this.oldResults
        },
        //确定
        hanldeConfirm(){
            this.visible = false
        },
        //查询员工列表
        queryListById(departInfo){
            let vm = this,
                param = {}
            vm.listLoading = true
            vm.curDepartId = departInfo.id //当前员工列表的部门
            vm.curDepartName = departInfo.name

            param.name = vm.filters.keyword
            param.deptid = departInfo.id
            queryEmployeeTreeById(param).then((res) => {
                vm.listLoading = false
                if (res.status === 10000) {
                    let data = res.data
                    vm.userList = data.datalist
                    data.datalist.forEach((item) => {
                        item.deptid = departInfo.id
                    })
                } else {
                    vm.$message({
                        showClose: true,
                        message: res.info,
                        type: 'error'
                    })
                }
            }).catch(() => { vm.listLoading = false })
        },
        //自定义树图标
        renderContent(h, { node, data, store }) {
            return (
            <span>
                <span><i class="el-icon-message"></i>&ensp;{node.label}</span>
            </span>)
        },
        //按照属性去重，只限数组内第一重对象
        unique(array, property){
            var r = [];
            for(var i = 0, l = array.length; i < l; i++) {
                for(var j = i + 1; j < l; j++)
                if (array[i][property] === array[j][property]) j = ++i
                r.push(array[i]);
            }
            return r
        },
    },
    watch: {
        results:function(newVal){
            this.$emit('input', newVal)
        }
    }
}
</script>
<style>
    .el-icon-message{
        color: #BBB;
    }
    .el-dialog__body{
        padding-top: 0;
    }
    .departBox{
        max-height: 150px;
        overflow: auto;
    }
    .deptName{
        font-size: 12px;
        line-height: 20px;
        color: #AAA;
    }
</style>

